#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# BSD License
# Copyright (c) 2011, Wang Qiang
# All rights reserved.

"""
Class represent a flow when html file is retrieved successfully.
"""
import os
import CustomError
from pyquery import PyQuery
from JQSelector.JQSelector import JQSelect, JQSelectPQ
from HtmlProcess import HtmlProcessor

class SuccessFlow(object):
    """
    Class represent a flow when html file is retrieved successfully.
    """
    def __init__(self, config, format):
        """
        Constructor for SuccessFlow
        """
        self.config = config
        self.format = format

    def processHtml(self, html):
        """
        process the html with the format information
        """
        self.res = self.parseHtml(html)
        self.addProperties()
        self.pushResult()

    def parseHtml(self, html):
        """
        parse html file with HtmlProcessor
        """
        processor = HtmlProcessor(self.format)
        processor.feedHtml(html)
        processor.extractFormat()
        processor.process()
        return processor.res

    def addProperties(self):
        basename, filename = os.path.split(self.format)
        _, category = os.path.split(basename)
        source, _ = os.path.splitext(filename)
        self.res['category'] = category
        self.res['source'] = source

    def pushResult(self):
        """
        Push the results to database.
        """
        raise NotImplementedError

class SimpleSuccessFlow(SuccessFlow):
    """
    SimpleSuccessFlow: print the results
    """
    def __init__(self, format):
        super(SimpleSuccessFlow, self).__init__(format)

    def pushResult(self):
        """
        Push the results to mongodb. 
        """
        print self.res

class MongoSuccessFlow(SuccessFlow):
    """
    MongoSuccessFlow: push the results into mongodb
    """
    def __init__(self, config, format):
        super(MongoSuccessFlow, self).__init__(config, format)

    def pushResult(self):
        """
        Push the results to mongodb. 
        """
        from pymongo import Connection
        # connect the mongodb
        connection = Connection(self.config.host, self.config.port)
        db = connection[self.config.dbname]
        collection = db[self.config.collection]
        #insert the res
        collection.insert(self.res)
        
class SuccessFlowFactory(object):
    """
    Factory for SuccessFlow
    """
    def __init__(self, config):
        super(SuccessFlowFactory, self).__init__()
        self.config = config
    
    def getSucessFlow(self, format):
        """
        Return a SucessFlow according to config
        """
        if self.config.dbtype == "mongodb":
            return MongoSuccessFlow(self.config, format)
